<template>
	<transition name="fade">
		<div class="goTop" @click="goTop()" v-if="ifShow">
			<img src="./goTop.png">
		</div>
	</transition>
</template>
<script>
export default {
	props:{
		// 离顶部多少距离才触发
		top:{
			type:Number,
			default:100
		},
		// 是否开启动画
		animation:{
			type:Boolean,
			default:false
		},
		// dom
		target:{
			type:String,
			//default: () => void 0
		},
	},
	watch: {
		target(v){
			console.log(v)
		}
	},
	data () {
		return {
			timer:"",
			ifShow:false
		}
	},
	methods:{
		//回到顶部
		goTop:function(){
			// 有动画
			if(this.animation){
				this.timer = setInterval(function () {
					let osTop = document.documentElement.scrollTop || document.body.scrollTop;
					let ispeed = Math.floor(-osTop / 5);
					document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
				},10)
			}
			// 没动画
			else{
				document.documentElement.scrollTop = 0;
			}
		}
	},
	mounted:function(){
		let dom = document.getElementById(this.target);
		//监听滚动，大于N才显示回到顶部
		dom.onscroll = (e)=>{
			let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			this.ifShow = dom.scrollTop>this.top?true:false;
			if(scrollTop == 0 && this.animation){
				clearInterval(this.timer)
			}
		}
	},
	created:function(){

	}
}
</script>

<style lang="scss" scoped>
	//回到顶部
	.goTop{
		position: fixed;
		right: 20px;
		bottom: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 50px;
		height: 50px;
		background-color: #409eff;
		opacity: 0.9;
		transition: all 0.3s;
		padding: 6px;
		cursor: pointer;
		img{
			width: 100%;
		}
	}
	.goTop:hover{
		opacity: 0.8;
		transition: all 0.3s;
	}
	//动画
	.fade-enter-active, .fade-leave-active {
		transition: opacity .3s;
	}
	.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
		opacity: 0;
	}
</style>
